﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main
{
    partial class AboutBox : Form
    {
        public AboutBox()
        {
            InitializeComponent();
            this.labelProductName.Text = AssemblyProduct;
            this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
            this.labelCopyright.Text = AssemblyCopyright;
            this.labelCompanyName.Text = AssemblyCompany;
            this.textBoxDescription.Text = AssemblyDescription;
        }

        #region Assembly Attribute Accessors

        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        public string AssemblyDescription
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyDescriptionAttribute)attributes[0]).Description;
            }
        }

        public string AssemblyProduct
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        public string AssemblyCopyright
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
            }
        }

        public string AssemblyCompany
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
                if (attributes.Length == 0)
                {
                    return "";
                }
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }
        #endregion

        private void btnUpadte_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] localFiles = Directory.GetFiles(Application.StartupPath, "*.*", SearchOption.TopDirectoryOnly);
            string msg = string.Empty;
            List<FileParameter> toUpdate = null;

            if (localFiles != null && localFiles.Length > 0)
            {
                List<FileParameter> lps = new List<FileParameter>();
                foreach (var item in localFiles)
                {
                    FileInfo fi = new FileInfo(item);
                    FileParameter fp = new FileParameter();
                    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(item);
                    fp.FileName = fi.Name;
                    fp.FolderPath = "UniRlv";
                    fp.FileSize = fi.Length;
                    fp.FileVer = fvi.ProductVersion;
                    fp.LastModifyTime = fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");

                    lps.Add(fp);
                }

                try
                {

                    RestClient.GetInstance().Method = EnumHttpVerb.POST;
                    RestClient.GetInstance().PostData = JsonHelper.ToJson(lps);
                    string resultPost = RestClient.GetInstance().HttpRequest("UniUpdateAPI/IfNeedUpdate");

                    if (!string.IsNullOrEmpty(resultPost))
                    {
                        toUpdate = JsonHelper.FromJson<List<FileParameter>>(resultPost);
                    }
                }
                catch (Exception exp)
                {
                    e.Result = exp.Message;
                    return;
                }
            }

            if (toUpdate != null && toUpdate.Count > 0)
            {
                e.Result = 2;
            }
            else
            {
                e.Result = 1;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int res = 0;

            if (int.TryParse(e.Result.ToString(), out res))
            {

                FileParameter fp;

                switch (res)
                {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2://有更新文件
                        if (MessageBox.Show("系统需要更新，是否立即升级？", "请确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                        {
                            Application.ExitThread();

                            fp = new FileParameter();
                            fp.FileName = Application.ExecutablePath;
                            fp.FolderPath = "UniRlv";

                            Process p = new Process();
                            p.StartInfo.FileName = Path.Combine(Application.StartupPath, "Update.exe");
                            string json = JsonHelper.ToJson(fp);
                            p.StartInfo.Arguments = Convert.ToBase64String(Encoding.GetEncoding("GBK").GetBytes(json));
                            p.Start();
                        }

                        return;
                    default:
                        break;
                }
            }
            else
            {
                MessageBox.Show("检测升级失败：" + e.Result);
            }
        }
    }
}
